package absolute_zero.com.urbox;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Configuration;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemSelectedListener;

public class urbox_send extends Activity {
    
/********************* INSTANCE VARIABLES **********************************/
	
	//Variables
	String[][] fileType = {
		{"Contact Info", "Send one of your address book contacts to someone else"},
		{"SD Card File", "Send a file from your SD card"},
		{"Business Card", "Send your information to someone else"},
		/*{"Ringtone", "Send a ringtone from your phone to someone else"},
		{"Wallpaper", "Send a Wallpaper from your phone to someone else"},
		{"Program", "Send a program from your phone to someone else"},
		{"Calendar event", "Send an event from your calendar to another"}*/
	};
	//String rootFile = "/sdcard";
	String rootFile = "/sdcard";
	
	//Send_FileType Screen Elements
	Spinner fileType_Spinner;
	TextView fileType_Info;
	Button back_to_main;
	Button continue1;
	
	//Send_File Screen Elements
	Button back_to_send_filetype;
	ListView fileBrowser;
	List<String> directoryEntries = new ArrayList<String>();
    File currentDirectory = new File(rootFile); 
    private Builder alert;
    private Builder confirm;
	
	//Transfer Screen Elements
	TextView transferInfo;
	ProgressBar progress;
	Button cancel;
	
	ArrayList<String> textTypeSpinner = new ArrayList<String>();
	int flag = 0;  //FLAG for going to correct screen
	
/******************* INITIALIZING METHODS ***********************************/
	
	/** Called when screen is turned **/
    @Override
    public void onConfigurationChanged(Configuration newConfig){
    	super.onConfigurationChanged(newConfig);
    }
	
	/** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.send_filetype);
        
        Log.d("Started urbox_send","Started correctly");
        
        //Setup Screen Elements
        fileType_Spinner = (Spinner)this.findViewById(R.id.filetype_spinner);
        fileType_Info = (TextView)this.findViewById(R.id.file_detail_info);
        back_to_main = (Button)this.findViewById(R.id.Back_to_main);
        continue1 = (Button)this.findViewById(R.id.Continue1);
        
        
        
    	//Initialize Spinner
        set_fileType_Spinner();
        
        //Add Button listeners
        back_to_main.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                //quit activity
            	finish();
                
            }
        });
        /**TODO: Finish setting button options*/
        continue1.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                //Decides what screen to go set based on file type
            	
            	if(flag == 0){
            		/*
            		  //Call Go to Contact search to find whos info you want to send
            		 
            		Intent i = new Intent(urbox_send.this, ContactChooser.class);
            		startActivityForResult(i, 0x34);
            		finish();
            		*/
            		//Call the warning popup
            		alert = new AlertDialog.Builder(urbox_send.this)
                	/**TODO: Finish setting options for buttons or make new menu*/
    	            .setTitle("Feature Not Available")
    	            .setMessage("This Feature is Only Available in the Full Version!")
    	            .setNeutralButton("OK", new DialogInterface.OnClickListener() {
    	                    public void onClick(DialogInterface dialog, int whichButton) {
    	                            //Do Nothing
    	                    }
    	            });
                alert.show();
            		
            	}
            	else if(flag == 1) {
            		//Go to file browser and find what we want to send
            		setContentView(R.layout.send_file);
            		browseToRoot();
               	}
            	else if(flag == 2) {
            		//Call Contact Search with your contact info
            		/*
            		Intent i = new Intent(urbox_send.this, ContactSearch.class);
            		startActivity(i);
            		*/
            		//call the warning popup
            		alert = new AlertDialog.Builder(urbox_send.this)
                	/**TODO: Finish setting options for buttons or make new menu*/
    	            .setTitle("Feature Not Available")
    	            .setMessage("This Feature is Only Available in the Full Version!")
    	            .setNeutralButton("OK", new DialogInterface.OnClickListener() {
    	                    public void onClick(DialogInterface dialog, int whichButton) {
    	                            //Do Nothing
    	                    }
    	            });
                alert.show();
            	}
            	else if(flag == 3) {
            		String uri = null;
                    Intent intent = new Intent( RingtoneManager.ACTION_RINGTONE_PICKER);
                    intent.putExtra( RingtoneManager.EXTRA_RINGTONE_TYPE, RingtoneManager.TYPE_NOTIFICATION);
                    intent.putExtra(RingtoneManager.EXTRA_RINGTONE_SHOW_SILENT, false);
                    intent.putExtra( RingtoneManager.EXTRA_RINGTONE_TITLE, "Select Tone");
                    if( uri != null)
                    {
                         intent.putExtra( RingtoneManager.EXTRA_RINGTONE_EXISTING_URI,
                    Uri.parse( uri));
                    }

                    else
                    {
                         intent.putExtra( RingtoneManager.EXTRA_RINGTONE_EXISTING_URI,
                    (Uri)null);
                    }
                    startActivityForResult( intent, 1337);
            	}
            }
        });
        

    }
    
    @Override
    protected void onActivityResult( int requestCode, int resultCode,
    Intent data ){
    	if(requestCode == 1337){
    		if (resultCode == RESULT_OK) {
                Uri uri = data.getParcelableExtra(RingtoneManager.EXTRA_RINGTONE_PICKED_URI);
                if (uri != null) {
                	String ringTonePath = uri.getPath();
                	File ringtonefile = new File(uri.toString());
                	//ringTonePath = ringTonePath + uri.get
                	Log.d("Path", ringTonePath);
                }
    		}

    	}else{
    		finish();
    	}
    	super.onActivityResult(requestCode, resultCode, data);
    } 



/****************** SELF-MADE METHODS **************************************/
    
    /**Code to set and display file info based on spinner*/
    private void set_fileType_Spinner() {
    	textTypeSpinner.clear();
    	for(int j = 0; j < fileType.length; j++){
    		if(!textTypeSpinner.contains(fileType[j][0])){
    			textTypeSpinner.add(fileType[j][0]);
    		}
    	}
    	ArrayAdapter<String> File_Types_Adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, textTypeSpinner);
    	File_Types_Adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    	fileType_Spinner.setAdapter(File_Types_Adapter);
   
    	fileType_Spinner.setOnItemSelectedListener(new OnItemSelectedListener(){
    		public void onItemSelected(AdapterView<?> arg0, View arg1,
					int position, long id){
    			fileType_Info.setText(fileType[position][1]);
    			
    			//Set FLAG to go to correct next screen
    			flag = position;
    		}

			public void onNothingSelected(AdapterView<?> arg0) {
				//DO NOTHING
			}
    	});
	
    }

    public void browseFiles(final File aDirectory){
    	//Check location  	
    	Log.d("Current Location:", aDirectory.toString());
    	Log.d("Is a Directory:", aDirectory.isDirectory() + "");
    	
        //Code to determine if folder or file and how to handle
        if (aDirectory.isDirectory()){
            this.currentDirectory = aDirectory;
            openFile(aDirectory);
        }
        else{
            alert = new AlertDialog.Builder(urbox_send.this)
            	/**TODO: Finish setting options for buttons or make new menu*/
	            .setTitle("File Options")
	            .setMessage("What do you want to do with this file?")
	            .setPositiveButton("Send", new DialogInterface.OnClickListener() {
	                    public void onClick(DialogInterface dialog, int whichButton) {
	                    	Intent i = new Intent(urbox_send.this, ContactSearch.class);
	                    	Bundle UserInfo = new Bundle();
	                        //Log.d("here's the file", aDirectory.getAbsolutePath());
	                    	UserInfo.putString("Filepath", aDirectory.getAbsolutePath());
	                        i.putExtras(UserInfo);
	                        startActivityForResult(i, 0x32);
	                    }
	            })
	            .setNeutralButton("Cancel", new DialogInterface.OnClickListener() {
	                    public void onClick(DialogInterface dialog, int whichButton) {
	                            //Do Nothing
	                    }
	            })
	            .setNegativeButton("Delete", new DialogInterface.OnClickListener() {
	                    public void onClick(DialogInterface dialog, int whichButton) {
	                    	confirmDialog(aDirectory, "delete");
	                    }
            });
            alert.show();
       } 
    }
    
    //Returns back to the root file (presumably the sdcard)
    public void browseToRoot(){
    	back_to_send_filetype = (Button)this.findViewById(R.id.Back_to_send_filetype);
        back_to_send_filetype.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
            	end();                  
            }

			private void end() {
				finish();
			}
        });
    	browseFiles(new File(rootFile));
    }
    
    //Goes up one folder in the directory
    public void upOneLevel(){
    	if(this.currentDirectory.getParent() != null && this.currentDirectory.getPath() != rootFile){
    		 browseFiles(this.currentDirectory.getParentFile());
    	}
    } 
    
    //Opens the folder clicked on
    public void openFile(File aFile){
        fill((aFile.getAbsoluteFile()).listFiles());
    } 
    
    // Checks whether checkItsEnd ends with one of the Strings from fileEndings 
    private boolean checkEndsWithInStringArray(String checkItsEnd,
                        String[] fileEndings){
         for(String aEnd : fileEndings){
              if((checkItsEnd.toLowerCase()).endsWith(aEnd))
                   return true;
         }
         return false;
    }
    
    //Displays and adds listeners to the files in a directory
    public void fill(final File files[]){
    	//Setup Browser
    	ListView fileBrowser = (ListView)findViewById(R.id.File_list);
    	//Set up adapter to Browser
		Icon_text_list_adapter itla = new Icon_text_list_adapter(this);
		
        // Add Items to Browser
        itla.addItem(new Icon_text(
               "Back to Root", getResources().getDrawable(R.drawable.back_arrow)));
        itla.addItem(new Icon_text(
               "Up-Folder", getResources().getDrawable(R.drawable.up_arrow)));
        
        for(int i = 0; i < files.length; i++){
        	if(files[i].isDirectory()){
        		itla.addItem(new Icon_text(
                		files[i].getName(), getResources().getDrawable(R.drawable.folder)));
        	}
        	else
        	
	            /* Determine the Icon to be used,
	             * depending on the FileEndings defined in:
	             * res/values/fileendings.xml. */
	            if(checkEndsWithInStringArray(files[i].getName(), getResources().
	                                getStringArray(R.array.fileEndingImage))){
	            	itla.addItem(new Icon_text(
	                		files[i].getName(), getResources().getDrawable(R.drawable.image)));
	            }
	            else if(checkEndsWithInStringArray(files[i].getName(), getResources().
	                                getStringArray(R.array.fileEndingWebText))){
	            	itla.addItem(new Icon_text(
	                		files[i].getName(), getResources().getDrawable(R.drawable.webtext)));
	            }
	            else if(checkEndsWithInStringArray(files[i].getName(), getResources().
	                                getStringArray(R.array.fileEndingPackage))){
	            	itla.addItem(new Icon_text(
	                		files[i].getName(), getResources().getDrawable(R.drawable.archive)));
	            }
	            else if(checkEndsWithInStringArray(files[i].getName(), getResources().
	                                getStringArray(R.array.fileEndingAudio))){
	            	itla.addItem(new Icon_text(
	                		files[i].getName(), getResources().getDrawable(R.drawable.audio)));
	            }
	            else if(checkEndsWithInStringArray(files[i].getName(), getResources().
	            					getStringArray(R.array.fileEndingText))){
	            	itla.addItem(new Icon_text(
	                		files[i].getName(), getResources().getDrawable(R.drawable.text)));
	            }    
	            else if(checkEndsWithInStringArray(files[i].getName(), getResources().
    								getStringArray(R.array.fileEndingVideo))){
	            	itla.addItem(new Icon_text(
	            			files[i].getName(), getResources().getDrawable(R.drawable.video)));
	            }
	            else{
	        		itla.addItem(new Icon_text(
	                		files[i].getName(), getResources().getDrawable(R.drawable.blank_file)));
	            }
	        }
        
        // Display it
        fileBrowser.setAdapter(itla);
        
        // Set the click listener
        fileBrowser.setOnItemClickListener(new OnItemClickListener(){

			public void onItemClick(AdapterView<?> arg0, View arg1,
					int arg2, long arg3) {
				// Make the files/directories clickable
				if(arg2 == 0){
					browseToRoot();
				}			
				else if(arg2 == 1){
					upOneLevel();
				}
				else {
					browseFiles(files[arg2 - 2]);
				}
			}
        });
    }
    public void confirmDialog(final File destroyDirectory, String action){
    	confirm = new AlertDialog.Builder(urbox_send.this)
    	.setMessage("Are you sure you wish to " + action + "?")
    	.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int whichButton) {
                		destroyDirectory.delete();
                		browseFiles(currentDirectory);
                }
        })
        .setNegativeButton("No", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int whichButton) {
                        //Do Nothing
                }
        });
    	confirm.show();
    }
}